﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.UI.DataVisualization;
using System.Web.UI.DataVisualization.Charting;
using System.Collections.Generic;
using System.Text;

using CE.Global;
using CE.Database;

public partial class sales_target : System.Web.UI.Page
{
    protected override void InitializeCulture()
    {
        String selectedCulture = CE.Global.General.SetCulture();
        base.InitializeCulture();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        //Session[CE.Global.General.Guest] = null;
        //{
        //    Response.Redirect("~/SiteUserSecureLogin.aspx");
        //}

        //if (Session[General.UserRole] != null && Session[General.UserRole].ToString() == "201")
        //{
        //    Response.Redirect("~/carinsurance/PendingApplication.aspx");
        //}

        string addrString = GetUser_IP();
        string validAddress = "58.137.119.114,182.52.226.198,210.19.137.50,210.195.132.255,::1,127.0.0.1";
        //if (!validAddress.Contains(addrString.Trim()))
        //{
        //    //Invalid IP
        //    //lblMessage.Text = "This is not a valid ip address.<br/>" +
        //    //                    "ip addres นี้ไม่อนุญาตให้ใช้งาน";
        //    return;
        //}

        if (!Page.IsPostBack)
        {
            if (validAddress.Contains(addrString.Trim()))
            {
                divSalesTarget.Visible = true;
                divSecurityLogin.Visible = false;
                PageLoad();
            }
            else if (Session[CE.Global.General.Guest] != null && Session[CE.Global.General.Guest].ToString().ToUpper() == "GGADMIN")
            {
                divSalesTarget.Visible = true;
                divSecurityLogin.Visible = false;
                PageLoad();
            }
            else
            {
                divSalesTarget.Visible = false;
                divSecurityLogin.Visible = true;
            }   
            //DrawChart();
            //DateTime _dateTime = General.GetUTCDateTime();
            //lblDate.Text = _dateTime.ToString("dddd MMMM dd, yyyy");
            //DateTime dateTimeNow = General.GetUTCDateTime();
            //string _strHur = dateTimeNow.ToString("hh");
            //string _strMin = dateTimeNow.ToString("mm");
            //string _strSec = dateTimeNow.ToString("ss");
            //txtHour.Text = _strHur;
            //txtMinute.Text = _strMin;
            //txtSecond.Text = _strSec;
        }
    }

    public void DrawChart()
    {
        StringBuilder strScript = new StringBuilder();
        try
        {
            MyDatabase _db = new MyDatabase();
            string _spName = "";
            DataSet _dsAmount = new DataSet();

            _spName = "sprocCXCRMAgentSalesTargetSelectedItemList";
            SortedList _paraList = new SortedList();
            _paraList.Add("@LoginType", "2");
            _dsAmount = _db.GetDataSet(_spName, _paraList);

            #region Chart Values
            DataTable _dtAgentSalesNew = new DataTable();
            DataTable _dtAgentSalesRenewal = new DataTable();

            if (_dsAmount != null && _dsAmount.Tables.Count > 0)
            {
                if (_dsAmount.Tables.Count > 1 && _dsAmount.Tables[1].Rows.Count > 0)
                {
                    _dtAgentSalesRenewal = _dsAmount.Tables[1];
                }
            }

            if (_dsAmount != null && _dsAmount.Tables.Count > 0)
            {
                if (_dsAmount.Tables.Count > 0 && _dsAmount.Tables[0].Rows.Count > 0)
                {
                    _dtAgentSalesNew = _dsAmount.Tables[0];
                }
            }

            #endregion

            #region Chart Old
            //if (_dtAgentSalesNew != null && _dtAgentSalesNew.Rows.Count > 0)
            //{
            //    string _Title = Resources.General.AgentsSalesRanking;
            //    strScript.Append(@"<script type='text/javascript'>");
            //    strScript.Append("window.onload = function() {");

            //    #region Chart New
            //    strScript.Append("var optionsNew = {");
            //    strScript.Append("title: {");
            //    strScript.Append("text: '" + _Title + "'");
            //    strScript.Append("},");
            //    strScript.Append("animationEnabled: true,");
            //    strScript.Append("data: [");
            //    strScript.Append("{");
            //    strScript.Append("type: 'line',");
            //    strScript.Append("dataPoints: [");

            //    foreach (DataRow row in _dtAgentSalesNew.Rows)
            //    {
            //        //if (row["IndividualAmount"].ToString() != "0")
            //        //{
            //        string _values = "{ x: " + row["AgentRank"].ToString() + ", y: " + row["IndividualAmount"].ToString() + " },";
            //        strScript.Append(_values);
            //        //}
            //    }
            //    strScript.Append("]");
            //    strScript.Append("}");
            //    strScript.Append("]");
            //    strScript.Append("};");
            //    #endregion

            //    #region Chart Renewal
            //    strScript.Append(" var optionsRenewal = {");
            //    strScript.Append("title: {");
            //    strScript.Append("text: '" + _Title + "'");
            //    strScript.Append("},");
            //    strScript.Append("animationEnabled: true,");
            //    strScript.Append("data: [");
            //    strScript.Append("{");
            //    strScript.Append("type: 'line',");
            //    strScript.Append("dataPoints: [");

            //    foreach (DataRow row in _dtAgentSalesRenewal.Rows)
            //    {
            //        //if (row["IndividualAmount"].ToString() != "0")
            //        //{
            //        string _values = "{ x: " + row["AgentRank"].ToString() + ", y: " + row["IndividualAmount"].ToString() + " },";
            //        strScript.Append(_values);
            //        //}
            //    }
            //    strScript.Append("]");
            //    strScript.Append("}");
            //    strScript.Append("]");
            //    strScript.Append("};");
            //    #endregion

            //    strScript.Append("$('#chartContainerNew').CanvasJSChart(optionsNew);");
            //    strScript.Append("$('#chartContainerRenewal').CanvasJSChart(optionsRenewal);");

            //    strScript.Append("}");
            //    strScript.Append("</script>");
            //}
            //ltScripts.Text = strScript.ToString();
            #endregion

            #region Chart New
            if (_dtAgentSalesNew != null && _dtAgentSalesNew.Rows.Count > 0)
            {
                strScript.Append(@"<script type='text/javascript'>");
                strScript.Append("window.onload = function () {");

                #region Chart New Sales
                strScript.Append(" var chart = new CanvasJS.Chart('chartContainerNew', {");
                strScript.Append("title:{");
                strScript.Append("text:''");
                strScript.Append("},");
                strScript.Append("animationEnabled: true,");
                strScript.Append("axisX:{");
                strScript.Append("interval: 1,");
                strScript.Append("labelFontSize: 12,");
                strScript.Append("lineThickness: 0");
                strScript.Append("},");
                strScript.Append("axisY2:{");
                strScript.Append("valueFormatString: ' 0',");
                strScript.Append("lineThickness: 0  ");
                strScript.Append("},");
                strScript.Append("toolTip: {");
                strScript.Append("shared: true");
                strScript.Append("},");
                strScript.Append("legend:{");
                strScript.Append("verticalAlign: 'top',");
                strScript.Append("horizontalAlign: 'center'");
                strScript.Append("},");
                strScript.Append("data: [");
                strScript.Append("{");
                strScript.Append("type: 'stackedBar',");
                strScript.Append("showInLegend: true,");
                strScript.Append("name: '" + Resources.General.Collection + "',");
                strScript.Append("axisYType: 'secondary',");
                //strScript.Append("color: '#f2b401',");
                strScript.Append("color: '#85b402',");
                strScript.Append("dataPoints: [");
                foreach (DataRow row in _dtAgentSalesNew.Rows)
                {
                    string _values = "{y: " + row["CollectedAmount"].ToString() + ", label: '" + row["AgentCodeId"].ToString() + "'},";
                    strScript.Append(_values);
                }
                strScript.Append("]");
                strScript.Append(" },");
                strScript.Append("{ ");
                strScript.Append("type: 'stackedBar',");
                strScript.Append("showInLegend: true,");
                strScript.Append("name: '" + Resources.General.TargetBalance + "',");
                strScript.Append("axisYType: 'secondary',");
                //strScript.Append("color: '#e68b00',");
                strScript.Append("color: '#cccccc',");
                strScript.Append("dataPoints: [");
                foreach (DataRow row in _dtAgentSalesNew.Rows)
                {
                    string _values = "{y: " + row["BalanceAmount"].ToString() + ", label: '" + row["AgentCodeId"].ToString() + "'},";
                    strScript.Append(_values);
                    //if (row["AgentId"].ToString() != "59141")
                    //{
                    //    string _values = "{y: " + row["BalanceAmount"].ToString() + ", label: '" + row["AgentCode"].ToString() + "'},";
                    //    strScript.Append(_values);
                    //}
                    //else
                    //{
                    //    string _values = "{y: 40000.50, label: '" + row["AgentCode"].ToString() + "'},";
                    //    strScript.Append(_values);
                    //}
                }
                strScript.Append("]");
                strScript.Append("},");
                strScript.Append("{");
                strScript.Append("type: 'stackedBar',");
                strScript.Append("showInLegend: true,");
                strScript.Append("name: '" + Resources.General.OverTraget + "',");
                strScript.Append("axisYType: 'secondary',");
                //strScript.Append("color: '#e55f00',");
                strScript.Append("color: '#f8d347',");
                strScript.Append("dataPoints: [");
                foreach (DataRow row in _dtAgentSalesNew.Rows)
                {
                    string _values = "{y: " + row["OvertheTarget"].ToString() + ", label: '" + row["AgentCodeId"].ToString() + "'},";
                    strScript.Append(_values);
                    //if (row["AgentId"].ToString() != "59141")
                    //{
                    //    string _values = "{y: " + row["OvertheTarget"].ToString() + ", label: '" + row["AgentCode"].ToString() + "'},";
                    //    strScript.Append(_values);
                    //}
                    //else
                    //{
                    //    string _values = "{y: 52000.50, label: '" + row["AgentCode"].ToString() + "'},";
                    //    strScript.Append(_values);
                    //}
                }
                strScript.Append("]");
                strScript.Append("}");
                strScript.Append("]");
                strScript.Append("});");
                strScript.Append(" chart.render();");
                #endregion

                #region Chart Renewal Sales
                strScript.Append(" var chartrenewal = new CanvasJS.Chart('chartContainerRenewal', {");
                strScript.Append("title:{");
                strScript.Append("text:''");
                strScript.Append("},");
                strScript.Append("animationEnabled: true,");
                strScript.Append("axisX:{");
                strScript.Append("interval: 1,");
                strScript.Append("labelFontSize: 12,");
                strScript.Append("lineThickness: 0");
                strScript.Append("},");
                strScript.Append("axisY2:{");
                strScript.Append("valueFormatString: ' 0',");
                strScript.Append("lineThickness: 0  ");
                strScript.Append("},");
                strScript.Append("toolTip: {");
                strScript.Append("shared: true");
                strScript.Append("},");
                strScript.Append("legend:{");
                strScript.Append("verticalAlign: 'top',");
                strScript.Append("horizontalAlign: 'center'");
                strScript.Append("},");
                strScript.Append("data: [");
                strScript.Append("{");
                strScript.Append("type: 'stackedBar',");
                strScript.Append("showInLegend: true,");
                strScript.Append("name: '" + Resources.General.Collection + "',");
                strScript.Append("axisYType: 'secondary',");
                strScript.Append("color: '#85b402',");
                strScript.Append("dataPoints: [");
                foreach (DataRow row in _dtAgentSalesRenewal.Rows)
                {
                    string _values = "{y: " + row["CollectedAmount"].ToString() + ", label: '" + row["AgentCodeId"].ToString() + "'},";
                    strScript.Append(_values);
                }
                strScript.Append("]");
                strScript.Append(" },");
                strScript.Append("{ ");
                strScript.Append("type: 'stackedBar',");
                strScript.Append("showInLegend: true,");
                strScript.Append("name: '" + Resources.General.TargetBalance + "',");
                strScript.Append("axisYType: 'secondary',");
                strScript.Append("color: '#cccccc',");
                strScript.Append("dataPoints: [");
                foreach (DataRow row in _dtAgentSalesRenewal.Rows)
                {
                    string _values = "{y: " + row["BalanceAmount"].ToString() + ", label: '" + row["AgentCodeId"].ToString() + "'},";
                    strScript.Append(_values);
                }
                strScript.Append("]");
                strScript.Append("},");
                strScript.Append("{");
                strScript.Append("type: 'stackedBar',");
                strScript.Append("showInLegend: true,");
                strScript.Append("name: '" + Resources.General.OverTraget + "',");
                strScript.Append("axisYType: 'secondary',");
                strScript.Append("color: '#f8d347',");
                strScript.Append("dataPoints: [");
                foreach (DataRow row in _dtAgentSalesRenewal.Rows)
                {
                    string _values = "{y: " + row["OvertheTarget"].ToString() + ", label: '" + row["AgentCodeId"].ToString() + "'},";
                    strScript.Append(_values);
                }
                strScript.Append("]");
                strScript.Append("}");
                strScript.Append("]");
                strScript.Append("});");
                strScript.Append(" chartrenewal.render();");
                #endregion

                strScript.Append("}");
                strScript.Append("</script>");
                ltScripts.Text = strScript.ToString();
            }
            #endregion

            #region Target Details
            string _month = General.GetUTCDateTime().ToString("MMM");
            float _Target = 0.0f;
            float _Collection = 0.0f;
            float _Balance = 0.0f;
            Int16 _Rank = 0;
            float _targetper = 0.0f;
            float _salesper = 0.0f;
            float _balanceper = 0.0f;
            Int32 _TotalWorkingDays = 0;
            Int32 _RemainWorkingDays = 0;
            Int32 _PastWorkingDays = 0;
            float _DailyTarget = 0.0f;
            float _TodayTarget = 0.0f;
            float _TodayCollection = 0.0f;

            int targetpercent = 0;
            string targetpercentdisplay = targetpercent.ToString() + "%";
            string targetcolor = "";
            int salepercent = 0;
            string salepercentdisplay = salepercent.ToString() + "%";
            string salecolor = "";
            int balancepercent = 0;
            string balancepercentdisplay = balancepercent.ToString() + "%";
            string balancecolor = "";

            if (_dsAmount != null && _dsAmount.Tables.Count > 3 && _dsAmount.Tables[3].Rows.Count > 0)
            {
                foreach (DataRow row in _dsAmount.Tables[3].Rows)
                {
                    foreach (DataColumn dc in _dsAmount.Tables[3].Columns)
                    {
                        string MonthCol = dc.ColumnName;
                        if (MonthCol == _month)
                        {
                            _Target = Convert.ToSingle(row[dc].ToString());
                        }
                    }
                }
            }

            if (_dsAmount != null && _dsAmount.Tables.Count > 4 && _dsAmount.Tables[4].Rows.Count > 0)
            {
                _Collection = Convert.ToSingle(_dsAmount.Tables[4].Rows[0]["IndividualAmount"].ToString());
                _Rank = Convert.ToInt16(_dsAmount.Tables[4].Rows[0]["AgentRank"].ToString());
                _TotalWorkingDays = Convert.ToInt32(_dsAmount.Tables[4].Rows[0]["TotalWorkingDays"].ToString());
                _RemainWorkingDays = Convert.ToInt32(_dsAmount.Tables[4].Rows[0]["RemainWorkingDays"].ToString());
                _PastWorkingDays = _TotalWorkingDays - _RemainWorkingDays;
            }

            if (_dsAmount != null && _dsAmount.Tables.Count > 5 && _dsAmount.Tables[5].Rows.Count > 0)
            {
                if (!float.TryParse(_dsAmount.Tables[5].Rows[0]["TodayCollection"].ToString(), out _TodayCollection))
                {
                    _TodayCollection = 0.0f;
                }
            }

            if (_Collection > 0)
            {
                _Balance = Convert.ToSingle(_Target - _Collection);
            }

            lblTotalTargetTitle.Text = Resources.General.TotalTarget;// "Total Target";
            lblTotalCollectionTitle.Text = Resources.General.TotalCollection;// "Total Collection";
            lblTargetBalanceTitle.Text = Resources.General.TargetBalance;// "Target Balance";
            lblTotalTarget.Text = Math.Ceiling(_Target).ToString("#,000.00");
            lblTotalCollection.Text = Math.Floor(_Collection).ToString("#,000.00");
            lblTargetBalance.Text = Math.Ceiling(_Balance).ToString("#,000.00");


            _DailyTarget = _Target / _TotalWorkingDays;
            _TodayTarget = _DailyTarget;
            if (_Target > 0)
            {
                _targetper = 100;
            }
            if (_Target > 0 && _Collection > 0)
            {
                _salesper = (_Collection / _Target) * 100;
            }
            if (_Target > 0 && _Balance > 0)
            {
                _balanceper = (_Balance / _Target) * 100;
            }

            #region Sales & Target - Values
            targetpercent = Convert.ToInt32(_targetper);
            targetpercentdisplay = targetpercent.ToString() + "%";
            targetcolor = "";
            salepercent = Convert.ToInt32(_salesper);
            salepercentdisplay = salepercent.ToString() + "%";
            salecolor = "";
            balancepercent = Convert.ToInt32(_balanceper);
            balancepercentdisplay = balancepercent.ToString() + "%";
            balancecolor = "";


            //Target
            if (targetpercent <= 25)
            {
                targetcolor = "#ff2c2c";
            }
            else if (targetpercent > 25 && targetpercent <= 50)
            {
                targetcolor = "#ff9212";
            }
            else if (targetpercent > 50 && targetpercent <= 75)
            {
                targetcolor = "#ffe012";
            }
            else if (targetpercent > 75)
            {
                targetcolor = "#71C73E";
            }

            //Sales
            if (salepercent <= 25)
            {
                salecolor = "#ff2c2c";
            }
            else if (salepercent > 25 && salepercent <= 50)
            {
                salecolor = "#ff9212";
            }
            else if (salepercent > 50 && salepercent <= 75)
            {
                salecolor = "#ffe012";
            }
            else if (salepercent > 75)
            {
                salecolor = "#71C73E";
            }

            //Balance
            if (balancepercent <= 25)
            {
                balancecolor = "#71C73E";
            }
            else if (balancepercent > 25 && balancepercent <= 50)
            {
                balancecolor = "#ffe012";
            }
            else if (balancepercent > 50 && balancepercent <= 75)
            {
                balancecolor = "#ff9212";
            }
            else if (balancepercent > 75)
            {
                balancecolor = "#ff2c2c";
            }
            //divTarget.Attributes.Add("data-text", targetpercentdisplay);
            //divTarget.Attributes.Add("data-percent", targetpercent.ToString());
            //divTarget.Attributes.Add("data-fgcolor", targetcolor);
            divCollection.Attributes.Add("data-text", salepercentdisplay);
            divCollection.Attributes.Add("data-percent", salepercent.ToString());
            divCollection.Attributes.Add("data-fgcolor", salecolor);
            divBalance.Attributes.Add("data-text", balancepercentdisplay);
            divBalance.Attributes.Add("data-percent", balancepercent.ToString());
            divBalance.Attributes.Add("data-fgcolor", balancecolor);
            #endregion

            #endregion
        }
        catch (Exception ex)
        {
        }
        finally
        {

        }
    }

    protected string GetUser_IP()
    {
        string VisitorsIPAddr = string.Empty;
        if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
        {
            VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
        }
        else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
        {
            VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
        }
        return VisitorsIPAddr;
    }

    public void PageLoad()
    {
        DrawChart();
        DateTime _dateTime = General.GetUTCDateTime();
        lblDate.Text = _dateTime.ToString("dddd MMMM dd, yyyy");
        DateTime dateTimeNow = General.GetUTCDateTime();
        string _strHur = dateTimeNow.ToString("hh");
        string _strMin = dateTimeNow.ToString("mm");
        string _strSec = dateTimeNow.ToString("ss");
        txtHour.Text = _strHur;
        txtMinute.Text = _strMin;
        txtSecond.Text = _strSec;
    }
    
    protected void btnSignIn_Click(object sender, EventArgs e)
    {
        if (IsValid)
        {
            if (txtSiteUser.Text == CE.Configuration.MyConfigurationManager.GetAppSettingValue("CXCRMAdminID"))
            {
                if (txtSiteUserAuthCode.Text == CE.Configuration.MyConfigurationManager.GetAppSettingValue("CXCRMAdminPass"))
                {
                    Session[CE.Global.General.Guest] = "GGADMIN";
                    divSalesTarget.Visible = true;
                    divSecurityLogin.Visible = false;
                    PageLoad();
                }
                else
                {
                    divSalesTarget.Visible = false;
                    divSecurityLogin.Visible = true;
                }
            }
        }
    }

}
